<template>
  <view
    class="pages-user-login"
    v-if="isLoad"
    :style="{ backgroundImage: `url(${imageUrl})` }">
    <uni-forms :modelValue="formData" class="from">
      <uni-forms-item name="phone">
        <input
          v-model="formData.phone"
          class="input"
          type="tel"
          placeholder="请输入手机号" />
      </uni-forms-item>
      <uni-forms-item name="code">
        <view
          style="
            display: flex;
            justify-content: space-between;
            background-color: #f4f6f8 !important;
            border-radius: 6px;
            padding: 24rpx;
          ">
          <input
            v-model="formData.code"
            type="number"
            placeholder="请输入验证码" />
          <text class="get-code" @click.stop="sendCode">
            {{ sending ? "获取中..." : timmer ? timmer + "秒" : "获取验证码" }}
          </text>
        </view>
      </uni-forms-item>
      <button
        class="sumbit"
        :loading="loading"
        :disabled="loading"
        @click="login">
        登录
      </button>
      <uni-forms-item style="margin-top: 48rpx">
        <checkbox-group @change="agreeChange">
          <checkbox
            :color="primaryColor"
            style="transform: scale(0.7)"
            :checked="formData.agree" />
          已详细阅读并同意
          <span @tap.stop="goDetail(1)" :style="{ color: primaryColor }">
            《用户隐私协议》
          </span>
          与
          <span @tap.stop="goDetail(2)" :style="{ color: primaryColor }">
            《个人信息保护指引》
          </span>
        </checkbox-group>
      </uni-forms-item>
    </uni-forms>
  </view>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
import siteInfo from "@/siteinfo.js";

export default {
  components: {},
  data() {
    return {
      imageUrl: "",
      isLoad: false,
      base_info: {},
      formData: {
        phone: "",
        code: "",
        agree: false,
      },
      sending: false,
      timmer: 0,
      loading: false,
    };
  },
  async onLoad() {
    const systemInfo = uni.getSystemInfoSync();
    if (
      systemInfo.platform === "devtools" ||
      systemInfo.platform === "ios" ||
      systemInfo.platform === "android"
    ) {
      // 可能是微信开发者工具或真机环境
      if (systemInfo.host && systemInfo.host.env === "WeChat") {
        console.log("微信小程序环境");
        let { siteroot } = siteInfo;
        let href = siteroot.split("index.php")[0];
        this.imageUrl = href + "/img/loginbg.png";
      } else {
        this.imageUrl = "../static/bg.png";
      }
    }

    let { autograph = "", appLogin = "" } = this;
    console.log("autograph,appLogin", autograph, appLogin);
    if (autograph && appLogin) {
      this.toLogin(appLogin);
      return;
    }
    let data = await this.$api.base.getConfig();
    this.base_info = data;
    if (!data.primaryColor) {
      data.primaryColor = "#A40035";
    }
    if (!data.subColor) {
      data.subColor = "#F1C06B";
    }
    let configInfo = Object.assign(this.$util.deepCopy(this.configInfo), data);
    this.updateConfigItem({
      key: "configInfo",
      val: configInfo,
    });
    this.isLoad = true;
  },
  computed: mapState({
    primaryColor: (state) => state.config.configInfo.primaryColor,
    subColor: (state) => state.config.configInfo.subColor,
    configInfo: (state) => state.config.configInfo,
    autograph: (state) => state.user.autograph,
    appLogin: (state) => state.user.appLogin,
    userInfo: (state) => state.user.userInfo,
  }),
  methods: {
    ...mapActions(["getConfigInfo", "getUserInfo"]),
    ...mapMutations(["updateConfigItem", "updateUserItem"]),
    async login() {
      if (this.loading) {
        return;
      }
      if (!/^1[3-9]\d{9}$/.test(this.formData.phone)) {
        this.$util.showToast({
          title: "请输入正确的手机号码",
        });
        return;
      }
      if (!this.formData.code) {
        this.$util.showToast({
          title: "请输入验证码",
        });
        return;
      }
      if (!this.formData.agree) {
        this.$util.showToast({
          title: "请详细阅读并同意《用户隐私协议》与《个人信息保护指引》",
        });
        return;
      }
      this.loading = true;
      this.$api.base
        .phoneLogin({
          phone: this.formData.phone,
          code: this.formData.code,
          agree: this.formData.agree ? 1 : 0,
        })
        .then(async (res) => {
          let { autograph, data } = res;
          this.updateUserItem({
            key: "userInfo",
            val: data,
          });
          this.updateUserItem({
            key: "autograph",
            val: autograph,
          });
          if (!this.configInfo.id) {
            await this.getConfigInfo();
          }
          this.$util.goUrl({
            url: `/pages/service`,
            openType: `reLaunch`,
          });
        })
        .catch((e) => {
          this.$util.showToast({
            title: e.response.data.error,
          });
          this.loading = false;
        });
    },
    sendCode() {
      if (this.sending || this.timmer) {
        return;
      }
      if (!/^1[3-9]\d{9}$/.test(this.formData.phone)) {
        this.$util.showToast({
          title: "请输入正确的手机号码",
        });
        return;
      }
      this.sending = true;
      this.$api.base
        .getLoginSmsCode({
          phone: this.formData.phone,
        })
        .then((res) => {
          this.timmer = 60;
          const interval = setInterval(() => {
            if (this.timmer <= 0) {
              clearInterval(interval);
              this.timmer = 0;
              return;
            }
            this.timmer--;
          }, 1000);
          this.sending = false;
        })
        .catch((e) => {
          this.$util.showToast({
            title: e.response.data.error,
          });
          this.sending = false;
        });
    },
    agreeChange(e) {
      this.formData.agree = !!e.detail.value.length;
    },
    //微信登录
    async wxLogin() {
      this.$refs.show_rule_item.close();
      try {
        let [providerErr, providerData] = await uni.getProvider({
          service: "oauth",
        });
        let [loginErr, loginData] = await uni.login({
          provider: "weixin",
        });
        let [infoErr, infoData] = await uni.getUserInfo({
          provider: "weixin",
        });

        let { userInfo = {} } = infoData;
        let { openId = "" } = userInfo;
        if (!openId) return;
        this.$util.showLoading({
          title: "登录中...",
        });
        try {
          this.toLogin(userInfo);
        } catch (e) {
          this.$util.hideAll();
        }
      } catch (e) {
        this.$util.showToast({
          title: "请先安装微信或升级版本",
        });
      }
    },
    async toLogin(userInfo) {
      let user_info = await this.$api.base.appLogin({
        data: userInfo,
      });
      this.updateUserItem({
        key: "appLogin",
        val: userInfo,
      });
      let { autograph, data } = user_info;
      this.$util.hideAll();
      this.updateUserItem({
        key: "userInfo",
        val: data,
      });
      this.updateUserItem({
        key: "autograph",
        val: autograph,
      });
      if (!this.configInfo.id) {
        await this.getConfigInfo();
      }
      let { phone = "" } = data;
      phone = 1;
      this.$util.goUrl({
        url: phone ? `/pages/service` : `/user/pages/phone`,
        openType: `reLaunch`,
      });
    },
    goDetail(type) {
      let { siteroot } = siteInfo;
      let href = siteroot.split("index.php")[0];
      let page = type == 1 ? "protocol" : "information";
      let url = `${href}${page}.html`;
      this.$util.goUrl({
        url,
        openType: "web",
      });
    },
  },
};
</script>

<style lang="scss">
page {
  background: #fff;
}

/* #ifdef H5 */
.pages-user-login {
  background-image: url("@/static/bg.png") !important;
}

/* #endif */
.pages-user-login {
  background-image: url("@/static/bg.png");
  background-size: cover;
  height: 100vh;

  .from,
  .uni-forms {
    background-color: #fff;
    border-radius: 32rpx;
    position: absolute;
    padding: 32rpx;
    width: calc(100% - 72rpx);
    margin: 0 36rpx;
    top: 320rpx;

    .input {
      background-color: #f4f6f8 !important;
      border-radius: 6px;
      padding: 24rpx;
    }

    .get-code {
      white-space: nowrap;
      // position: absolute;
      // top: 0;
      // right: 10px;
      // height: 92rpx;
      // line-height: 92rpx;
    }

    .sumbit {
      background-color: #8ffcc4;
      color: #fff;
    }
  }
}
</style>
